package Client;

import java.io.File;
import java.util.Random;

import DBUtil.CNN;
import Server.ClientAcceptEvent;
import Server.ClientException;
import Server.ClientExitEvent;
import Server.ClientRequestEvent;
import Server.Server;
import Server.ServerListener;
import Tools.Log;
import XML.XMLNode;

public class ClientServer implements ServerListener {
	public Server s;

	public ClientServer() {
		boolean b;
		Random r = new Random();
		int port = 9000;
		XMLNode xn = null;
		try {
			xn = (XMLNode) CNN.getConfig().GetPathValue("User.Share");
			port = Integer.valueOf(xn.get("ServPort"));
		} catch (Exception e) {
		}
		do {
			b = false;
			try {
				s = new Server(port);// 绑定服务端套接字
				Log.print("[ClientServer]Port :" + port);
			} catch (Exception e) {
				port = 1000 + r.nextInt(9000);// 产生一个端口号
				xn.put("ServPort", String.valueOf(port));
				b = true;
			}
		} while (b);
		if (xn != null) {
			CNN.getConfig().createCode(new File("Config.xml"));
		}
	}

	@Override
	public void accepClientEvent(ClientAcceptEvent ace) {

		Log.print("[用户进入]" + ace);
	}

	public void addListener(ServerListener sl) {
		s.addListener(sl);
	}

	@Override
	public void ClientCloseEvent(ClientExitEvent cce) {

		Log.print("[用户离开]" + cce);
	}

	@Override
	public void ClientException(ClientException e) {
		// TODO Auto-generated method stub

	}

	public int getPort() {
		return s.getLocalPort();
	}

	public void removeListener(ServerListener sl) {
		s.removeListener(sl);
	}

	@Override
	public void requestEvent(ClientRequestEvent se) {

		Log.print("[请求到达]" + se);
	}
}
